package com.fubowen.lepton.ui.reader.recycler

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.fubowen.lepton.helper.DBHelper
import com.fubowen.reader.book.impl.WebBook
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class BookChapterPagingSource(private val bookId: Int) : PagingSource<Int, BookChapter>() {
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, BookChapter> {
        return try {
           
            val pageIndex = params.key ?: 1
            val takeCount = params.loadSize
            val skipCount = (pageIndex - 1) * takeCount
            val list = DBHelper.db.bookDao().getPageChapter(bookId, takeCount, skipCount)
            list.forEach { downloadContent(it) }
            LoadResult.Page(
                data = list,
                prevKey = if (pageIndex == 1) null else pageIndex.minus(1),
                nextKey = if (list.isEmpty()) null else pageIndex.plus(1)
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }

    override fun getRefreshKey(state: PagingState<Int, BookChapter>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            val anchorPage = state.closestPageToPosition(anchorPosition)
            anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
        }
    }

    private fun downloadContent(chapter: BookChapter) {
        if (chapter.isDownload || chapter.url == null) {
            return
        }
        CoroutineScope(Dispatchers.IO).launch {
            WebBook.getChapterContent(chapter.url) {
                DBHelper.db.bookDao().setChapterContent(chapter.id, it, it.length)
            }
        }
    }
}